var app = getApp()
var chatInput = require('../../chat/chat-input/chat-input.js');
var timer;
var ping_user_id;
var ping_chat_to_uid;
let heartCheck = {
  timeout: 10000,
  timeoutObj: null,
  serverTimeoutObj: null,
  reset: function () {
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    return this;
  },
  start: function () {
    this.timeoutObj = setTimeout(() => {
      console.log("发送ping");
      let tmpPing = {
        ping: true,
        user_id: ping_user_id,
        target_id: ping_chat_to_uid,
      }
      tmpPing = JSON.stringify(tmpPing);
      wx.sendSocketMessage({
        data: tmpPing,
        success() {
          console.log("发送ping成功", tmpPing);
        }
      });
      this.serverTimeoutObj = setTimeout(() => {
        // wx.closeSocket();
        wx.closeSocket((res) => {
          console.log('serverTimeoutObj 卸载创建 的  WebSocket')
        })
      }, this.timeout);
    }, this.timeout);
  }
};


Page({

  /**
   * 页面的初始数据
   */
  data: {
    /*自己to_uid*/
    user_id: '',
    /*对方to_uid*/
    chat_to_uid: '',
    /*员工端会话chatid*/
    chatid: '',
    /*对方昵称*/
    contactUserName: '',
    /*自己头像*/
    chatAvatarUrl: '',
    /*对方头像*/
    toChatAvatarUrl: '',
    messageDate: '',
    messageList: [],
    lockReconnect: false,   //断线检查状态
    limit: 0, //断线检查计数
    closeReconnect: false,  //是否关闭断线重连 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options, "/////////////**99999999999999999999*********")
    if (options.contactUserName) {
      that.setData({
        contactUserName: options.contactUserName, 
      })
      wx.setNavigationBarTitle({
        title: options.contactUserName
      })
    }
    if (options.chat_to_uid) {
      that.setData({
        chat_to_uid: options.chat_to_uid
      })
      ping_user_id = wx.getStorageSync("userid");
      ping_chat_to_uid = options.chat_to_uid;
    }
    if (options.chatAvatarUrl) {
      that.setData({
        chatAvatarUrl: options.chatAvatarUrl
      })
    }
    if (options.toChatAvatarUrl) {
      that.setData({
        toChatAvatarUrl: options.toChatAvatarUrl
      })
    }

    that.setData({
      user_id: wx.getStorageSync("userid")
    })

    if (options.chatid) {
      that.setData({
        'chatInfo.chat_id': options.chatid
      })
      that.getMessageList();
    } else if (!options.chatid) {
      that.getChat();
    }

    that.initData();

  },


  /**
   * 连接WebSocket
   */
  linkSocket() {
    let that = this
    that.closeReconnect = false; //启动断线重连
    that.limit = 0;
    wx.connectSocket({
      url: app.globalData.wssUrl,
      success() {
        console.log('连接成功')
        that.initEventHandle()
      }
    })
  },
  /**
   * 启动监听WebSocket
   */
  initEventHandle() {
    let that = this
    wx.onSocketMessage((res) => {
      //收到消息
      if (res.data == "pong") {
        console.log('WebSocket连接正常....')
        heartCheck.reset().start()
      } else {
        //处理数据
        console.log('收到服务器内容：', res)
        var resData = JSON.parse(res.data);
        console.log('收到服务器内容resData：', resData)
        console.log(that.data.chat_to_uid, that.data.user_id, "0000000000000000")
        if (resData.data != '') {
          console.log("res.data不为空", resData.data)
          let data = {
            user_id: that.data.chat_to_uid,
            target_id: that.data.user_id,
            content: resData.data,
            uniacid: app.siteInfo.uniacid
          }

          var tmpData = that.data.messageList;
          var length = tmpData.length;
          console.log(that.data.messageList, "that.data.messageList")


          if (length > 0) {
            tmpData[length - 1].list.push(data);
            that.setData({
              messageList: tmpData
            }, function () {
              that.pageScrollToBottom()
            })
          } else {
            var date = new app.util.date();
            var create_time = (date.dateToLong(new Date) / 1000).toFixed(0);
            create_time = date.dateToStr('yyyy-MM-DD HH:mm:ss', date.longToDate(create_time * 1000));

            console.log(create_time, "////***555")
            tmpData.push({ create_time: create_time, list: [data] });
            that.setData({
              messageList: tmpData
            }, function () {
              that.pageScrollToBottom()
            })
          }
          console.log("res.data不为空 messageList", that.data.messageList)

        }
      }
    })

    wx.onSocketOpen(() => {
      console.log('WebSocket连接打开')
      heartCheck.reset().start();
    })
    wx.onSocketError((res) => {
      console.log('WebSocket连接打开失败')
      this.reconnect()
    })
    wx.onSocketClose((res) => {
      console.log('WebSocket 已关闭！')
      this.reconnect()
    })
  },
  /**
   * 卸载创建的WebSocket
   */
  unloadWebSocket() {
    var that = this;
    console.log('开始卸载 WebSocket')
    this.closeReconnect = true; // 关闭断线重连
    heartCheck.reset();  //关闭心跳
    wx.closeSocket((res) => {
      console.log('卸载创建 的  WebSocket')
    })
  },
  /**
   * 断线重连
   */
  reconnect() {
    //取消断线重连
    console.log('closeReconnect', this.closeReconnect, this.timer);
    if (this.closeReconnect) {
      clearTimeout(this.timer);
      this.closeReconnect = true;
      this.lockReconnect = false;
      return true;
    }
    console.log('closeReconnect', this.closeReconnect, this.timer);
    if (this.lockReconnect && this.closeReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer)
    if (this.data.limit < 12) {
      this.timer = setTimeout(() => {
        this.linkSocket();
        this.lockReconnect = false;
      }, 5000);
      this.setData({
        limit: this.data.limit + 1
      })
    } else {
      //当重新链接超过12次以后, 
      //提示客服重新链接 
      wx.navigateBack();
    }
  },



  onReady: function () {
    console.log("页面渲染完成")
  },
  onShow: function () {
    console.log("页面显示")
    this.reconnect();
  },
  onHide: function () {
    console.log("页面隐藏")
    // this.unloadWebSocket();
  },
  onUnload: function () {
    console.log("页面卸载")
    this.unloadWebSocket();
  },
  onPullDownRefresh: function () {
    // console.log("监听用户下拉动作")
    var that = this;
    that.setData({
      show: true
    })
    that.getMessageList();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },
  onReachBottom: function () {
    // console.log("监听页面上拉触底")  
  },
  onPageScroll: function (e) {
    //console.log("监听页面滚动", e);
  },
  onShareAppMessage: function (res) {
    // console.log("用户点击右上角分_享")
  },
  initData: function () {
    let that = this;
    let systemInfo = wx.getSystemInfoSync();
    chatInput.init(this, {
      systemInfo: systemInfo,
      minVoiceTime: 1,
      maxVoiceTime: 60,
      startTimeDown: 56,
      format: 'mp3',//aac/mp3
      sendButtonBgColor: 'mediumseagreen',
      sendButtonTextColor: 'white',
      extraArr: [
        {
          picName: 'choose_picture',
          description: '照片'
        }
        , {
          picName: 'take_photos',
          description: '拍摄'
        },
      ],
      // tabbarHeigth: 48
    });

    that.setData({
      pageHeight: systemInfo.windowHeight,
    });
    that.textButton();
  },
  textButton: function () {
    var that = this;
    chatInput.setTextMessageListener(function (options) {
      //jingshuixian 同步参数获取
      var success = options.success,
        e = options.e,
        fail = options.fail;

      let content = e.detail.value;
      console.log("userid**********************", that.data.user_id, that.data.chat_to_uid)
      let data = {
        user_id: that.data.user_id,
        target_id: that.data.chat_to_uid,
        content: content,
        uniacid: app.siteInfo.uniacid
      }
      data = JSON.stringify(data)
      console.log(data, "*************************************")

      wx.sendSocketMessage({
        data: data,
        success: function (res) {
          console.log(res, "success");
          var tmpData = that.data.messageList;
          var length = tmpData.length;

          data = JSON.parse(data);
          console.log(data, "*************************************")

          if (length > 0) {
            tmpData[length - 1].list.push(data);
            that.setData({
              messageList: tmpData
            }, function () {
              that.pageScrollToBottom()
            })
          } else {

            var date = new app.util.date();
            var create_time = (date.dateToLong(new Date) / 1000).toFixed(0);
            create_time = date.dateToStr('yyyy-MM-DD HH:mm:ss', date.longToDate(create_time * 1000));

            console.log(create_time, "////***555")
            tmpData.push({ create_time: create_time, list: [data] });

            that.setData({
              messageList: tmpData
            }, function () {
              that.pageScrollToBottom()
            })
          }

          var date = new app.util.date();
          var currentTime = (date.dateToLong(new Date) / 1000).toFixed(0);

          console.log("SendTemplate 客户发送给员工 模板消息")
          that.SendTemplateCilent(currentTime);

          success(true) //jingshuixian 同步结果  发送消息状态,用于判断是否清空文本框
        },
        fail: function (res) {
          console.log(res, "fail")
          fail(false) //jingshuixian 同步结果  发送消息状态,用于判断是否清空文本框
        }
      })

    });
  },
  pageScrollToBottom: function () {
    wx.createSelectorQuery().select('.speak_box').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      console.log(rect)
      wx.pageScrollTo({
        scrollTop: rect.height
      })
    }).exec()
  },
  SendTemplateCilent: function (currentTime) {
    var that = this;
    console.log(that.data.chat_to_uid, "chat_to_uid")
    app.util.request({
      'url': 'entry/wxapp/SendTemplateCilent',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        client_id: that.data.chat_to_uid,
        date: currentTime
      },
      success: function (res) {
        console.log("entry/wxapp/SendTemplateCilent ==>", res)
        if (!res.data.errno) {
        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  },
  getChat: function () {
    var that = this;
    app.util.request({
      'url': 'entry/wxapp/chatId',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        to_uid: that.data.chat_to_uid
      },
      success: function (res) {
        console.log("entry/wxapp/chatId ==>", res)
        if (!res.data.errno) {
          that.setData({
            chatInfo: res.data.data,
            chatAvatarUrl: res.data.data.user_info.avatarUrl,
            toChatAvatarUrl: res.data.data.target_info.avatarUrl
          })
          that.getMessageList();
        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  },
  getMessageList: function () {
    var that = this;
    var paramData = {
      chat_id: that.data.chatInfo.chat_id
    }
    if (that.data.messageDate) {
      paramData.create_time = that.data.messageDate
    }
    app.util.request({
      'url': 'entry/wxapp/messages',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': paramData,
      success: function (res) {
        console.log("entry/wxapp/messages ==>", res)
        if (!res.data.errno) {
          var tmpData = res.data.data.list;
          if (tmpData.length == 0) {
            that.setData({
              more: false,
              loading: false,
              isEmpty: true,
              show: true
            })
            return false;
          }

          that.setData({
            loading: true,
            messageDate: res.data.data.create_time
          })

          var tmpListData = that.data.messageList;

          tmpListData = tmpListData.reverse();

          var date = new app.util.date();
          // if (res.data.data.create_time.length < 12) {
          //     tmpCreateTime = date.dateToStr('yyyy-MM-DD HH:mm:ss', date.longToDate(res.data.data.create_time * 1000));
          // }
          var tmpCreateTime;
          for (let i in tmpData) {
            if (tmpData[i].create_time.length < 12) {
              tmpData[i].create_time = date.dateToStr('yyyy-MM-DD HH:mm:ss', date.longToDate(tmpData[i].create_time * 1000));
            }
            tmpCreateTime = tmpData[0].create_time;
            // tmpListData.push(tmpData[i]);
          }
          tmpData = tmpData.reverse();

          tmpListData.push({ create_time: tmpCreateTime, list: tmpData })

          tmpListData = tmpListData.reverse();


          that.setData({
            messageList: tmpListData
          })

          that.linkSocket();
        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  },
  formSubmit: function (e) {
    var that = this;
    var formId = e.detail.formId;
    that.toSaveFormIds(formId);
  },
  toSaveFormIds: function (formId) {
    var that = this;
    app.util.request({
      'url': 'entry/wxapp/formid',
      'cachetime': '30',
      'showLoading': false,
      'method': 'POST',
      'data': {
        formId: formId
      },
      success: function (res) {
        // console.log("entry/wxapp/formid ==>", res)
        if (!res.data.errno) {
        }
      },
      fail: function (res) {
        console.log("fail ==> ", res)
      }
    })
  }
});